package com.cloud.async.business.enums;

public enum TaskStatus {
    /**
     * 任务生命周期状态枚举
     */
    // 定义任务生命周期状态
    CREATED("CREATED", "任务创建", "任务创建"),
    RUNNING("RUNNING", "任务执行", "任务执行"),
    SUCCESS("SUCCESS", "任务成功", "任务成功"),
    FAILED("FAILED", "任务失败", "任务失败"),
    EXCEPTION("EXCEPTION", "任务异常", "任务异常"),
    CANCELLED("CANCELLED", "任务取消", "任务取消"),
    TIMEOUT("TIMEOUT", "任务超时", "任务超时");

    private final String code;         // 状态码（可用于持久化）
    private final String displayName;  // 显示名称（用于日志/UI）
    private final String description;  // 详细描述

    TaskStatus(String code, String displayName, String description) {
        this.code = code;
        this.displayName = displayName;
        this.description = description;
    }

    // Getter 方法
    public String getCode() {
        return code;
    }

    public String getDisplayName() {
        return displayName;
    }

    public String getDescription() {
        return description;
    }

    /**
     * 检查当前状态是否允许流转到目标状态
     *
     * @param targetState 目标状态
     * @return 是否允许流转
     */
    public boolean canTransitionTo(TaskStatus targetState) {
        switch (this) {
            case CREATED:
                return targetState == RUNNING || targetState == CANCELLED;
            case RUNNING:
                return targetState == SUCCESS
                        || targetState == FAILED
                        || targetState == EXCEPTION
                        || targetState == TIMEOUT;
            case SUCCESS:
            case FAILED:
            case EXCEPTION:
            case CANCELLED:
            case TIMEOUT:
                return false; // 终态不可流转
            default:
                return false;
        }
    }

    /**
     * 根据状态码查找枚举
     */
    public static TaskStatus fromCode(String code) {
        for (TaskStatus state : values()) {
            if (state.code.equalsIgnoreCase(code)) {
                return state;
            }
        }
        throw new IllegalArgumentException("未知的任务状态码: " + code);
    }

    @Override
    public String toString() {
        return displayName + "（" + code + "）";
    }
}
